package com.example.demo.filter;

import com.example.demo.exception.LogoutFailedException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LogoutExceptionFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (LogoutFailedException e) {
            // 将 ServletResponse 转换为 HttpServletResponse
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            // 设置响应状态码为 400，表示请求无效
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            // 设置响应的内容类型为 JSON 格式，并指定字符编码为 UTF-8
            httpResponse.setContentType("application/json;charset=UTF-8");

            // 创建一个包含错误信息的 Map
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", httpResponse.getStatus());
            errorResponse.put("message", e.getMessage());

            // 将错误信息转换为 JSON 字符串并写入响应体
            String jsonResponse = new ObjectMapper().writeValueAsString(errorResponse);
            httpResponse.getWriter().write(jsonResponse);
        }
    }
}
